<template>
  <div class="box">
    <NavBackVue title="购物车" right-text="清空"></NavBackVue>
    <div class="no-img">
      <img src="../../assets/imgs/R-C.png" alt="" v-if="isimgNaN" />
    </div>
    <div class="content-box">
      <van-checkbox-group
        v-model="checkedGoods"
        ref="checkboxGroup"
        @change="backControl"
      >
        <van-swipe-cell v-for="(item, index) in cartList" :key="item.cartid">
          <div style="display: flex">
            <van-checkbox
              :name="item.cartid"
              @click="() => changeCheckedItem(item.cartid)"
            ></van-checkbox>
            <van-card
              style="flex: 1"
              :price="item.originprice"
              :desc="item.proname.substring(0, 10)"
              class="goods-card"
              :thumb="item.img1"
            >
              <template #footer>
                <van-stepper
                  v-model="item.num"
                  :name="item.cartid"
                  @plus="changeNum(item, '+')"
                  @minus="changeNum(item, '-')"
                />
              </template>
            </van-card>
          </div>
          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
              @click="deleteList(item.cartid, index)"
            />
          </template>
        </van-swipe-cell>
      </van-checkbox-group>
    </div>
    <div class="footer-box">
      <van-submit-bar
        style="bottom: 50px"
        :price="totalMoney()"
        button-text="提交订单"
        :disabled="disabled"
        @submit="goconfirmorder"
      >
        <van-checkbox
          v-model="allChecked"
          :indeterminate="isIndeterminate"
          @change="allChange"
          >全选</van-checkbox
        >
      </van-submit-bar>
      <MyFooterVue></MyFooterVue>
    </div>
  </div>
</template>

<script>
import NavBackVue from "../../components/NavBack.vue";
import MyFooterVue from "../../components/footer.vue";
import { showFailToast, showConfirmDialog } from "vant";

export default {
  name: "shoppingcart",
  components: { NavBackVue, MyFooterVue },
  data() {
    return {
      allChecked: false,
      isIndeterminate: false,
      // 当前选中的商品。
      checkedGoods: [],
      // 购物车数据
      cartList: [],
      disabled: false,

      // 选中进下个页面的数据
      trueList: {},
    };
  },
  created() {
    this.getCartList();
  },
  computed: {
    isimgNaN() {
      if (this.cartList.length == "") {
        return true;
      } else {
        return false;
      }
    },
    disabled() {
      if (this.cartList.length == "") {
        return true;
      } else {
        return false;
      }
    },
  },
  methods: {
    // 点击按钮去订单页
    goconfirmorder() {
      if (
        this.checkedGoods != "" &&
        this.cartList.filter((item) => item.flag == true)
      ) {
        // console.log(this.checkedGoods);
        console.log("this.cartList", this.cartList);
        console.log('所有为true的数据',this.cartList.filter((item) => item.flag == true));
        this.trueList = this.cartList.filter((item) => item.flag == true);
        console.log("this.trueList", this.trueList);
        localStorage.setItem("cartList", JSON.stringify(this.trueList));
        this.$router.push({
          // path: "./confirmorder",
        });
      } else {
        showFailToast("商品没有勾选");
      }
    },
    onClickRight() {
      if (this.cartList.length != "") {
        showConfirmDialog({
          title: "确认清空购物车吗",
          message: "亲,确认清空购物车吗",
        })
          .then(() => {
            this.$http({
              url: "/cart/removeall",
              method: "post",
              data: {
                userid: localStorage.getItem("userid"),
              },
            }).then((res) => {
              if (res.data.code === "200") {
              }
            });
            // on confirm
            this.cartList = [];
          })
          .catch(() => {
            // on cancel
          });
      } else {
        showFailToast("还没有东西快去添加");
      }
    },
    // 获取用户名之下的购物车
    getCartList() {
      this.$http({
        url: "/cart/list",
        method: "post",
        data: {
          userid: localStorage.getItem("userid"),
        },
      }).then((res) => {
        if (res.data.code === "200") {
          this.cartList = res.data.data;
          // console.log(this.cartList);
          this.cartList.forEach((item) => {
            if (item.flag) {
              this.checkedGoods.push(item.cartid);
            }
          });
          this.backControl();
        }
      });
    },
    // 反向控制
    backControl() {
      if (this.checkedGoods.length === 0) {
        this.allChecked = false;
        this.isIndeterminate = false;
      } else if (this.checkedGoods.length === this.cartList.length) {
        this.allChecked = true;
        this.isIndeterminate = false;
      } else {
        this.allChecked = false;
        this.isIndeterminate = false;
      }
    },
    // 按钮全选设置
    allChange() {
      if (this.allChecked == true) {
        this.$refs.checkboxGroup.toggleAll(true);
      } else {
        this.$refs.checkboxGroup.toggleAll();
      }

      this.$http({
        url: "/cart/selectall",
        method: "post",
        data: {
          userid: localStorage.getItem("userid"),
          type: this.allChecked,
        },
      });
    },
    // 小计金额
    totalMoney() {
      return (
        this.cartList.reduce((preValue, item) => {
          return (
            preValue +
            (this.checkedGoods.includes(item.cartid)
              ? item.originprice * item.num
              : 0)
          );
        }, 0) * 100
      );
    },
    // 更新购物车数量
    async changeNum(item, operator) {
      try {
        const res = await this.$http({
          url: "/cart/updatenum",
          method: "post",
          data: {
            cartid: item.cartid,
            num: operator === "+" ? item.num + 1 : item.num - 1,
          },
        });

        if (res.data.code === "200") {
        } else {
          showFailToast("数量更新失败！");
          operator === "+" ? item.num-- : item.num++;
        }
      } catch (err) {
        showFailToast("数量更新失败！");
        if (operator === "+") {
          item.num--;
        } else if (operator === "-") {
          item.num++;
        }
      }
    },
    // 单选按钮
    changeCheckedItem(cartid) {
      this.$http({
        url: "/cart/selectone",
        method: "post",
        data: {
          cartid,
          flag: this.checkedGoods.some((item) => item === cartid),
        },
      }).then((res) => {
        if (
          res.data.code === "200" &&
          this.checkedGoods.some((item) => item === cartid)
        ) {
          // showSuccessToast("")
          // console.log(this.checkedGoods.some((item) => item === cartid));
          // console.log(this.checkedGoods);
          this.checkedGoods.push(cartid);
          // this.cartList.filter((item) => item.flag == true)
        } else {
        }
      });
    },
    deleteList(cartid, index) {
      showConfirmDialog({
        title: "确认删除吗",
        message: "亲,您不要我了嘛",
      })
        .then(() => {
          this.$http({
            url: "/cart/remove",
            method: "post",
            data: {
              cartid,
            },
          }).then((res) => {
            if (res.data.code === "200") {
            }
          });
          // on confirm
          this.cartList.forEach((item) => {
            if (cartid == item.cartid) {
              this.cartList.splice(index, 1);
            }
          });
        })
        .catch(() => {
          // on cancel
        });
    },
  },
};
</script>

<style scoped>
.box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.footer-box {
  height: 100px;
}

.content-box {
  flex: 1;
  width: 100%;
  overflow-y: auto;
}
.no-img img {
  width: 100%;
}
.van-swipe-cell {
  align-items: center;
}
</style>